package com.fingard.dsp.bank.directbank.nbcb01;

import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsHisBalDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class NBCB01Balance extends NBCB01Base implements IBalance {

    //单个余额查询和批量余额查询，统一采用流处理方式
    //1、循环调用Req7506BalQry.readRecord()读取一个请求明细，然后写入发银行的XML对象
    //2、发银行
    //3、循环调用XmlTextReader.read()读取一个银行返回节点，赋值返回ATS的明细对象，
    //   然后调用RetAts7506BalQry.writeRetDetail()，写入返回ATS的明细
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {//余额查询
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        if (p_req7506.isBatch == true) {//批量余额查询
            return d_7506_qryBatch(p_req7506, retAts);

        } else {
            return d_7506_qrySingle(p_req7506, retAts);//单笔余额查询
        }
    }

    public RetAts7506BalQry d_7506_qryBatch(Req7506BalQry p_req7506, RetAts7506BalQry retAts) throws Exception {
        try {
            //赋值通用参数
            serviceId = "srv004_batchAccountInfoQuery";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter);
            if (!"".equals(bankFront.token)) {
                xmlWriter.writeElementString("functionId", "srv004");
                xmlWriter.writeElementString("functionName", "账户余额(批量)");
                xmlWriter.writeStartElement("opReq");
                xmlWriter.writeElementString("serialNo", p_req7506.reqHeader.transSeqID);
                xmlWriter.writeElementString("reqTime", Format.DateTime14Format.format(new Date()));
                xmlWriter.writeStartElement("ReqParam");
                xmlWriter.writeElementString("SHMU", String.valueOf(p_req7506.detailCount));
                xmlWriter.writeStartElement("list");
                while (p_req7506.readRecord()) {
                    xmlWriter.writeStartElement("row");
                    xmlWriter.writeElementString("ZHHA", p_req7506.readedDetail.actNum);
                    xmlWriter.writeEndElement();
                }
                xmlWriter.writeEndElement();
                xmlWriter.writeEndElement();
                xmlWriter.writeEndElement();
                String signXml = getDataSignData(xmlWriter);
                if (signnatrue(signXml) == true) {
                    xmlWriter.writeElementString("signData", signature);
                    xmlWriter.writeEndDocument();
                    if (bankFront.lastVisitTime != null) {
                        long timeSpan = -bankFront.lastVisitTime.getTime() + new Date().getTime();
                        long waitSecsQryBal = Long.valueOf(getBankConfig().getValueAsString("waitSecsQryBal")) * 1000;
                        if (timeSpan < waitSecsQryBal) {
                            long sleepMils = waitSecsQryBal - timeSpan;
                            this.WriteBankLogLn2("sleep(" + sleepMils + ")");
                            Thread.sleep(sleepMils);
                        }
                    }
                    String[] tmpStrRet = sendToBank(getDataSendBank(xmlWriter.toXmlString()));
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                        if (tmpBkReader != null) {
                            String tmpStatus = tmpBkReader.getFirstText("/NBCBEBankData/retCode");
                            String tmpStatusText = tmpBkReader.getFirstText("/NBCBEBankData/errorMsg");
                            if (tmpStatus != null && isActiveRetCode(tmpStatus)) {
                                while (tmpBkReader.read("/NBCBEBankData/opRep/list/row")) {
                                    RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
                                    tmpRetDetail.respCode = "0";
                                    tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("ZHHA");
                                    tmpRetDetail.actCur = convertCurToATS(tmpBkReader.readedXElement.getSingleText("BIZH"));
                                    tmpRetDetail.actArea = tmpBkReader.readedXElement.getSingleText("KHWD");
                                    tmpRetDetail.availBal = tmpBkReader.readedXElement.getSingleText("KYER");
                                    tmpRetDetail.currBal = tmpBkReader.readedXElement.getSingleText("YUER");
                                    retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                                }
                            } else {
                                retAts.writeRespCode("-1");
                                retAts.writeRespInfo(tmpStatusText);
                            }
                        } else {
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo(tmpSbMsg.toString());
                        }
                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmpStrRet[1]);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSign[1]);
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo("登录失败");
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }

    public RetAts7506BalQry d_7506_qrySingle(Req7506BalQry p_req7506, RetAts7506BalQry retAts) throws Exception {
        try {
            //赋值通用参数
            serviceId = "srv003_singleAccountInfoQuery";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter);
            if (!"".equals(bankFront.token)) {
                xmlWriter.writeElementString("functionId", "srv003");
                xmlWriter.writeElementString("functionName", "账户余额（单笔）");
                int count = 0;
                Date date = new Date();
                while (p_req7506.readRecord()) {
                    count++;
                    String actNum = p_req7506.readedDetail.actNum;
                    xmlWriter.writeStartElement("opReq");
                    xmlWriter.writeElementString("serialNo", p_req7506.reqHeader.transSeqID);
                    xmlWriter.writeElementString("reqTime", Format.DateTime14Format.format(date));
                    xmlWriter.writeStartElement("ReqParam");
                    xmlWriter.writeElementString("ZHHA", actNum);
                    xmlWriter.writeEndElement();
                    xmlWriter.writeEndElement();
                    /*String signXml =  "<serialNo>"+p_req7506.reqHeader.transSeqID+"</serialNo><reqTime>"+Format.DateTime14Format.format(date)+"</reqTime><ReqParam><ZHHA>"+actNum+"</ZHHA></ReqParam>" ;*/
                }
                String signXml = getDataSignData(xmlWriter);
                if (signnatrue(signXml) == true) {
                    xmlWriter.writeElementString("signData", signature);
                    xmlWriter.writeEndDocument();
                    if (bankFront.lastVisitTime != null) {
                        long timeSpan = -bankFront.lastVisitTime.getTime() + new Date().getTime();
                        long waitSecsQryBal = Long.valueOf(getBankConfig().getValueAsString("waitSecsQryBal")) * 1000;
                        if (timeSpan < waitSecsQryBal) {
                            long sleepMils = waitSecsQryBal - timeSpan;
                            this.WriteBankLogLn2("sleep(" + sleepMils + ")");
                            Thread.sleep(sleepMils);
                        }
                    }
                    String[] tmpStrRet = sendToBank(getDataSendBank(xmlWriter.toXmlString()));
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                        if (tmpBkReader != null) {
                            String tmpStatus = tmpBkReader.getFirstText("/NBCBEBankData/retCode");
                            String tmpStatusText = tmpBkReader.getFirstText("/NBCBEBankData/errorMsg");
                            if (tmpStatus != null && isActiveRetCode(tmpStatus)) {
                                while (tmpBkReader.read("/NBCBEBankData/opRep/opResult")) {
                                    RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
                                    tmpRetDetail.respCode = "0";
                                    tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("ZHHA");
                                    tmpRetDetail.availBal = tmpBkReader.readedXElement.getSingleText("KYER");
                                    tmpRetDetail.currBal = tmpBkReader.readedXElement.getSingleText("YUER");

                                    retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                                }
                            } else {
                                retAts.writeRespCode("-1");
                                retAts.writeRespInfo(tmpStatusText);
                            }
                        } else {
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo(tmpSbMsg.toString());
                        }
                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmpStrRet[1]);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSign[1]);
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo("登录失败");
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        RetAts7505HisBalQry retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            //赋值通用参数
            serviceId = "srv054_queryDayBalance";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter);
            if (!"".equals(bankFront.token)) {
                xmlWriter.writeElementString("functionId", "srv054");
                xmlWriter.writeElementString("functionName", "日终余额查询");
                xmlWriter.writeStartElement("opReq");
                xmlWriter.writeElementString("serialNo", p_req7505.reqHeader.transSeqID);
                xmlWriter.writeElementString("reqTime", Format.DateTime14Format.format(new Date()));
                xmlWriter.writeStartElement("ReqParam");
                xmlWriter.writeElementString("ZHHA", p_req7505.actNum);//查询账号
                xmlWriter.writeElementString("KSSJ", DateHelper.convertD8toD10(p_req7505.dateFrom));//开始日期
                xmlWriter.writeElementString("JSSJ", DateHelper.convertD8toD10(p_req7505.dateTo));//结束日期
                xmlWriter.writeEndElement();//ReqParam
                xmlWriter.writeEndElement();//opReq
                String signXml = getDataSignData(xmlWriter);
                if (signnatrue(signXml) == true) {
                    xmlWriter.writeElementString("signData", signature);
                    xmlWriter.writeEndDocument();
                    if (bankFront.lastVisitTime != null) {
                        long timeSpan = -bankFront.lastVisitTime.getTime() + new Date().getTime();
                        long waitSecsQryBal = Long.valueOf(getBankConfig().getValueAsString("waitSecsQryBal")) * 1000;
                        if (timeSpan < waitSecsQryBal) {
                            long sleepMils = waitSecsQryBal - timeSpan;
                            this.WriteBankLogLn2("sleep(" + sleepMils + ")");
                            Thread.sleep(sleepMils);
                        }
                    }

                    String[] tmpStrRet = sendToBank(getDataSendBank(xmlWriter.toXmlString()));
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                        if (tmpBkReader != null) {
                            String tmpStatus = tmpBkReader.getFirstText("/NBCBEBankData/retCode");
                            String tmpStatusText = tmpBkReader.getFirstText("/NBCBEBankData/errorMsg");
                            if (tmpStatus != null && isActiveRetCode(tmpStatus)) {
                                while (tmpBkReader.read("/NBCBEBankData/opRep/list")) {
                                    RetAtsHisBalDetail tmpRetDetail = new RetAtsHisBalDetail();
                                    tmpRetDetail.actBal = tmpBkReader.readedXElement.getSingleText("YUER");//余额
                                    tmpRetDetail.balDate = tmpBkReader.readedXElement.getSingleText("JYRQ");//YYYY-MM-DD
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpStatusText;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpStrRet[1];
                    }

                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpSign[1];
                }
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = "登录失败";
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("返回结果为空，所查询时间段内不存在历史余额");
        }
        retAts.writeEnd();
        return retAts;
    }

}
